﻿// -----------------------------
// Copyright © Kodi Studios 2012
// -----------------------------

using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text.RegularExpressions;

namespace Kodi.Picturethrill
{
    public class Updater
    {
        public static bool NewVersionAvailable()
        {
            try
            {
                PublishedUpdate publishedUpdate = new PublishedUpdate();
                publishedUpdate.Init();

                FileVersionInfo currentFileVersionInfo = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location);
                if (publishedUpdate.Version > Version.Parse(currentFileVersionInfo.ProductVersion))
                {
                    return true;
                }
            }
            catch (Exception e)
            {
                Log.Comment(e.ToString());
            }

            return false;
        }

        private static bool Update(string url)
        {
            try
            {
                // Copy file to temp
                // Check web for updates
                WebClient webClient = new WebClient();

                // Check version
                string latestProgramPathLocal = Path.Combine(Settings.TempPath, Path.GetFileName(url));
                webClient.DownloadFile(url, latestProgramPathLocal);

                string commandLine = Process.GetCurrentProcess().GetCommandLine();

                //"C:\Projects\Picturethrill\Picturethrill\Picturethrill\bin\Debug\Picturethrill.vshost.exe" -ioio fff
                Match match = Regex.Match(commandLine, @"\""[^\""]+\""(.*)");
                string commandLineArgs = string.Empty;

                if (match.Success)
                {
                    commandLineArgs = " -nor -ra " + "\"" + match.Groups[1].Value + "\""; // probably need to escape quotes
                }

                // Launch with special flag
                Process.Start(latestProgramPathLocal, "-r " + Assembly.GetEntryAssembly().Location + commandLineArgs);
                return true;
            }
            catch (Exception e)
            {
                Log.Comment(e.ToString());
            }

            return false;
        }
    }
}
